package org.idea.spring.bean.scope;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

/**
 * @Author linhao
 * @Date created in 1:47 下午 2021/5/2
 */
public class UserBeanScopeLookUpDemo {

    @Bean
    //默认是单例对象
    public static User singletonUser(){
        return createUser(System.nanoTime());
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public static User prototypeUser(){
        return createUser(System.nanoTime());
    }

    @Autowired
    @Qualifier("singletonUser")
    public User singletonUser1;

    @Autowired
    @Qualifier("singletonUser")
    public User singletonUser2;

    @Autowired
    @Qualifier("prototypeUser")
    public User prototypeUser1;

    @Autowired
    @Qualifier("prototypeUser")
    public User prototypeUser2;



    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
        annotationConfigApplicationContext.register(UserBeanScopeLookUpDemo.class);
        annotationConfigApplicationContext.refresh();
        UserBeanScopeLookUpDemo beanScopeLookUpDemo = annotationConfigApplicationContext.getBean(UserBeanScopeLookUpDemo.class);
        System.out.println(beanScopeLookUpDemo.prototypeUser1 == beanScopeLookUpDemo.prototypeUser2);
        System.out.println(beanScopeLookUpDemo.singletonUser1 == beanScopeLookUpDemo.singletonUser2);
//        lookUpBean(annotationConfigApplicationContext);
        annotationConfigApplicationContext.close();

    }

    public static void lookUpBean(AnnotationConfigApplicationContext annotationConfigApplicationContext){
        for(int i=0;i<3;i++){
            User singletonUser = annotationConfigApplicationContext.getBean("singletonUser",User.class);
            System.out.println(singletonUser.toString());
            User prototypeUser = annotationConfigApplicationContext.getBean("prototypeUser",User.class);
            System.out.println(prototypeUser.toString());
        }
    }

    public static User createUser(long time){
        User user = new User();
        user.setTime(time);
        user.setUsername("idea");
        return user;
    }
}
